﻿using FyCaches.Core.Msg;
using FyCaches.Core.Services;
using FyCaches.Models;
using FySystem.Extension;
using FySystem.Net.SimSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FyCaches.Core.CommandHandlers
{
    internal class PublishCommand
    {
        /// <summary>
        /// 推送
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        internal static int Handle(CommandInfo command)
        {
            int res = -1;
            try
            {
                //主题长度
                ushort length = BitConverter.ToUInt16(command.Frame.Frame, 40);

                //主题
                string topic = Encoding.UTF8.GetString(command.Frame.Frame, 42, length);

                //clientId长度
                ushort clength = BitConverter.ToUInt16(command.Frame.Frame, 42 + length);

                //clientId
                byte[] clientId = command.Frame.Frame.ReadBytes(44 + length, clength);

                //内容
                byte[] msg = command.Frame.Frame.ReadBytes(44 + length + clength);

                //找出匹配的主题的连接
                List<SubscribeInfo> subscribes = MessageService.GetTopicMatchConnections(topic);

                if (subscribes.IsNullOrEmpty() == false)
                {
                    foreach(var item in subscribes)
                    {
                        var pack = PackUtils.CreatePackForPublish(command, topic, item.Topic, ref clientId, ref msg);

                        if (item.SimClients.IsNullOrEmpty() == false)
                        {
                            foreach (var conn in item.SimClients)
                            {
                                try
                                {
                                    if (conn.IsConnect)
                                    {
                                        conn.Send(pack);
                                        res++;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    FyLogContext.Write(ex.Message);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }
    }
}
